package org.example.classtopia.Service.Impl;

import jakarta.servlet.http.HttpServletRequest;
import org.example.classtopia.Common.Result.Result;
import org.example.classtopia.Mapper.UserFollowMapper;
import org.example.classtopia.Model.Entity.User;
import org.example.classtopia.Model.Entity.UserFollow;
import org.example.classtopia.Model.Entity.UserMessage;
import org.example.classtopia.Model.dto.FindDataByIDDTO;
import org.example.classtopia.Model.vo.FindDataByIDVO;
import org.example.classtopia.Model.vo.FolloweeVO;
import org.example.classtopia.Model.vo.PostPreviewVO;
import org.example.classtopia.Service.UserFollowService;
import org.example.classtopia.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;

    @Autowired
    private UserMessageService userMessageService;


    private static final int STATUS_ACTIVE = 1;
    private static final int STATUS_INACTIVE = 0;

    private void sendFollowMessage(Long followerId, Long followeeId) {
        try {
            // 从数据库获取关注者昵称，或者默认用ID代替
            String nickname = getUserNickname(followerId);

            UserMessage msg = new UserMessage();
            msg.setUserId(followeeId);
            msg.setMessageType("system");
            msg.setContent(nickname + " 关注了你。");
            msg.setIsRead(0);
            msg.setTime(LocalDateTime.now());

            userMessageService.saveMessage(msg);
        } catch (Exception e) {
            // 仅记录异常，不影响主流程
            // 这里可以用日志框架记录异常
            System.err.println("发送关注消息失败：" + e.getMessage());
        }
    }

    private void sendUnfollowMessage(Long followerId, Long followeeId) {
        try {
            String nickname = getUserNickname(followerId);

            UserMessage msg = new UserMessage();
            msg.setUserId(followeeId);
            msg.setMessageType("system");
            msg.setContent(nickname + " 取关了你。");
            msg.setIsRead(0);
            msg.setTime(LocalDateTime.now());

            userMessageService.saveMessage(msg);
        } catch (Exception e) {
            System.err.println("发送取关消息失败：" + e.getMessage());
        }
    }

    private String getUserNickname(Long userId) {
        User user = userMessageService.getUserById(userId); // 你需要在 UserMessageService 或 UserMapper里实现对应获取用户的方法
        if (user != null && user.getNickname() != null) {
            return user.getNickname();
        }
        return "用户ID " + userId;
    }

    @Override
    public boolean follow(Long followerId, Long followeeId) {
        if (followerId == null || followeeId == null || followerId.equals(followeeId)) {
            return false; // 不能关注自己或空ID
        }
        // 先尝试更新已有关注状态为有效
        int updatedRows = userFollowMapper.updateStatus(followerId, followeeId, STATUS_ACTIVE);
        if (updatedRows > 0) {
            // 已有记录，更新成功，说明之前可能取消过，重新关注
            sendFollowMessage(followerId, followeeId);
            return true; // 更新成功，表示之前关注过，现在重新关注
        }
        // 没有历史记录，插入新关注
        UserFollow userFollow = new UserFollow();
        userFollow.setFollowerId(followerId);
        userFollow.setFolloweeId(followeeId);
        userFollow.setStatus(STATUS_ACTIVE);

        boolean inserted = userFollowMapper.insert(userFollow) > 0;
        if (inserted) {
            sendFollowMessage(followerId, followeeId);
        }

        return inserted;
    }

    @Override
    public boolean unfollow(Long followerId, Long followeeId) {
        if (followerId == null || followeeId == null) {
            return false;
        }
        int updatedRows = userFollowMapper.updateStatus(followerId, followeeId, STATUS_INACTIVE);
        if (updatedRows > 0) {
            sendUnfollowMessage(followerId, followeeId);
            return true;
        }
        return false;
    }

    @Override
    public List<FolloweeVO> getFollowees(Long followerId) {
        if (followerId == null) {
            return null;
        }
        return userFollowMapper.selectFolloweesByFollowerId(followerId, STATUS_ACTIVE);
    }

    @Override
    public List<PostPreviewVO> getPostsByUserId(Long userId) {
        if (userId == null) {
            return null;
        }
        return userFollowMapper.selectPostsByUserId(userId);
    }

    @Override
    public boolean isFollowing(Long followerId, Long followeeId) {
        if (followerId == null || followeeId == null) {
            return false;
        }
        int count = userFollowMapper.countByFollowerIdAndFolloweeIdAndStatus(followerId, followeeId, STATUS_ACTIVE);
        return count > 0;
    }

}

